import axios from "axios";
import router from '@/router'
import { ip, versionKey } from '@/api/config'
import { Message } from "element-ui";

const request = axios.create({
    baseURL: ip,
    timeout:'5000s'
})

request.interceptors.request.use(config=>{
    if(localStorage.getItem('token')){
        config.headers['token'] = `${localStorage.getItem('token')}`
    }
    config.headers['versionKey'] = versionKey;
    return config;
})

request.interceptors.response.use(res=>{
    if(res.headers['token']){
        localStorage.setItem('token', res.headers['token'])
    }
    if(res.data.code != 200){
        Message.warning(res.data.msg || '操作失败')
    }
    if(res.data.code == 403){
        localStorage.removeItem('token')
        router.replace('/login').catch(()=>{})
    }
    return res.data;
},
err=>{
    Message.error('请检查当前网络可用')
    return Promise.reject(new Error(err))
})

export default request;